const fs = require('fs')
const path = require('path')
class RenamePlugin {
  constructor(option) {
    this.option = option
  }
  apply(compiler) {
    compiler.hooks.emit.tap('addPrefix', compilation => {
      const targetPath = path.join(__dirname, '../')
      this.removeDir(targetPath + 'lastdist')
      fs.existsSync(targetPath + 'lastdist') && fs.rmdirSync(targetPath + 'lastdist')
      fs.rename(targetPath + 'blogdist', targetPath + 'lastdist', e => {
        e ? console.log(e) : console.log('更名成功')
      })
    })
  }
  removeDir(targetPath) {
    if (!fs.existsSync(targetPath)) {
      return
    }
    const fileStat = fs.statSync(targetPath)
    // 判断是否为文件夹，如果是，则递归
    if (fileStat.isDirectory()) {
      const fileArr = fs.readdirSync(targetPath)
      fileArr.forEach(item => {
        this.removeDir(`${targetPath}/${item}`)
      })
    } else {
      //是文件，则删除
      fs.unlinkSync(targetPath)
    }
  }
}
module.exports = RenamePlugin
